package com.bnlr.lrparking.appui.mine.recentparkrecord;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.constant.ConstantFlag;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.model.Location;
import com.bnlr.lrparking.widget.NativeDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * description: 最近停车记录页面
 * RecentParkRecordActivity class
 *
 * @author : Licy
 * @date : 2018/12/26
 */
public class RecentParkRecordActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.iv_nav_back)
    ImageView ivNavBack;
    @BindView(R.id.p_r_recycle)
    RecyclerView recycleView;
    @BindView(R.id.p_r_swipe)
    SwipeRefreshLayout refreshLayout;

    @BindView(R.id.ll_hint)
    LinearLayout noData;
    @BindView(R.id.iv_hint)
    ImageView noDataivhint;
    @BindView(R.id.tv_hint_tips)
    TextView noDatatvHint;

    private Context mContext;
    private RecentParkRecordAdapter adapter;
    private List<RecentParkRecordBean.DataBean> mDataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_latestparkingrecord);
        ButterKnife.bind(this);
        mContext = this;

        initView();
        initSwipe();
        initRecycle();
        initListener();

        getListData();
        refreshLayout.setRefreshing(true);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        adapter.disableLoadMoreIfNotFullPage();

        getListData();
    }

    /**
     * 初始化页面内容
     */
    public void initView() {
        tvNavTitle.setText("停车记录");
    }

    /**
     * 初始化刷新控件
     */
    public void initSwipe() {

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LogUtils.i("begin refresh!");
                // 下拉刷新
                getListData();

            }
        });

    }

    /**
     * 初始化recycle view
     */
    public void initRecycle() {

        mDataList = new ArrayList<>();
        adapter = new RecentParkRecordAdapter(R.layout.item_parkingrecord, mDataList);
        recycleView.setAdapter(adapter);

        // 开启item动画
        adapter.openLoadAnimation();
        // 设置布局管理器
        recycleView.setLayoutManager(new LinearLayoutManager(this));
        // 设置item的动画效果 默认
        recycleView.setItemAnimator(new DefaultItemAnimator());
        // 自定义 recycle view 间隔
        recycleView.addItemDecoration(new SpaceItemDecoration(10));

        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                LogUtils.i("start load more!");
                getListData();
            }
        }, recycleView);
        // 第一次进入不上拉加载，必须写在setOnLoadMoreListener后面
        adapter.disableLoadMoreIfNotFullPage();

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                if (mDataList.get(i).getStatus().equals("1")) {
                    ToastUtils.showShort("您的订单还未生成哦~~");
                } else {
                    startActivity(new Intent(mContext, RecentParkRecordDetailActivity.class)
                            .putExtra("orderNum", mDataList.get(i).getOrderNum()));
                }

            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                /**
                 * 先判断是不是登陆，检测地图工具
                 */
                if (AppConfig.getInstance().getBoolean("isLogin", false)) {
                    Location locNow = new Location(Params.CurrentLat, Params.CurrentLon, "我的位置");
                    Location locEnd = new Location(mDataList.get(i).getLat(), mDataList.get(i).getLng(), mDataList.get(i).getAddress());
                    NativeDialog msgDialog = new NativeDialog(RecentParkRecordActivity.this, locNow, locEnd);
                    msgDialog.show();
                } else {
                    startActivity(VerificaActivity.class);
                }

            }
        });

    }

    /**
     * 初始化监听
     */
    public void initListener() {

        ivNavBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }


    /**
     * 获取数据
     */
    public void getListData() {

        mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
        mRequest.add("action", "GetOrderDay");
        mRequest.add("phonePara", Application.DEVICE_ID);
        mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

        CallServer.getRequestInstance().add(
                this, mRequest,
                new CustomHttpListener<RecentParkRecordBean>(this, true, RecentParkRecordBean.class) {

                    @Override
                    public void doWork(RecentParkRecordBean data, String code) {

                        if (AppConfig.DEBUG) {
                            LogUtils.d("RecentParkRecordBean", data.toString());
                        }

                        if (TextUtils.equals("1", code)) {
                            switchView(true);
                            if (adapter != null) {
                                if (!data.getData().isEmpty()) {
                                    mDataList.clear();
                                    mDataList.addAll(data.getData());
                                    if (refreshLayout.isRefreshing()) {
                                        adapter.setNewData(mDataList);
                                    } else {
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                                if (refreshLayout.isRefreshing()) {
                                    refreshLayout.setRefreshing(false);
                                }
                                if (adapter.isLoading()) {
                                    adapter.loadMoreEnd();
                                }
                            }
                        } else {
                            switchView(false);
                        }

                    }

                    @Override
                    public void onFinally(JSONObject obj, String code, boolean isSucceed) throws JSONException {
                        super.onFinally(obj, code, isSucceed);

                        switchView(code.equals(ConstantFlag.STRING_FLAG_ONE));

                        if (refreshLayout.isRefreshing()) {
                            refreshLayout.setRefreshing(false);
                        }
                        if (adapter.isLoading()) {
                            adapter.loadMoreEnd();
                        }
                    }
                }, false);


    }

    /**
     * 自定义 recycle view 间隔
     */
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;

        /**
         * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
         * the number of pixels that the item view should be inset by, similar to padding or margin.
         * The default implementation sets the bounds of outRect to 0 and returns.
         * <p>
         * <p>
         * If this ItemDecoration does not affect the positioning of item views, it should set
         * all four fields of <code>outRect</code> (left, top, right, bottom) to zero
         * before returning.
         * <p>
         * <p>
         * If you need to access Adapter for additional data, you can call
         * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
         * View.
         *
         * @param outRect Rect to receive the output.
         * @param view    The child view to decorate
         * @param parent  RecyclerView this ItemDecoration is decorating
         * @param state   The current state of RecyclerView.
         */
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = mSpace;
//            if (parent.getChildAdapterPosition(view) == 0) {
//                outRect.top = mSpace;
//            }

        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }


    /**
     * 切换页面
     *
     * @param isHaveData 是否有数据
     */
    public void switchView(boolean isHaveData) {
        LogUtils.i("switchView start + isHaveData " + isHaveData);

        if (isHaveData) {
            refreshLayout.setVisibility(View.VISIBLE);
            noData.setVisibility(View.GONE);
            noDatatvHint.setVisibility(View.GONE);
            noDataivhint.setVisibility(View.GONE);
        } else {
            refreshLayout.setVisibility(View.GONE);
            noData.setVisibility(View.VISIBLE);
            noDatatvHint.setVisibility(View.VISIBLE);
            noDatatvHint.setText("暂无数据~~");
            noDataivhint.setVisibility(View.VISIBLE);
            noDataivhint.setImageResource(R.mipmap.norecord);
        }
    }

}
